package ee.serge.server.template;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import ee.serge.server.ArticleServiceImpl;
import ee.serge.server.PublicServiceImpl;

public abstract class Template {

   protected static final PublicServiceImpl publicServiceImpl = new PublicServiceImpl();
   protected static final ArticleServiceImpl articleServiceImpl = new ArticleServiceImpl();
   private static final String baseTemplate;
   protected Map<String, String> paramMap;
   private String template;
   
   static {
      baseTemplate = read("template/htmltemplate.html");
   }
   
   public Template(String query) throws Exception {
      template = baseTemplate;
      paramMap = new HashMap<String, String>();
      query = query.replace("!", "");
      String[] pairs = query.split("[?&]");
      for (String pair : pairs) {
         String[] hold = pair.split("=");
         if (hold.length == 2) {
            paramMap.put(hold[0], hold[1]);
         } else if (hold.length == 1) {
            paramMap.put(null, hold[0]);
         }
      }
      init();
      replace("title", getTitle());
      replace("header", getHeader());
      replace("header2", getHeader2());
      replace("content", getContent());
   }
   
   protected abstract void init() throws Exception;
   protected abstract String getTitle();
   protected abstract String getHeader();
   protected abstract String getHeader2();
   protected abstract String getContent();

   public void replace(String oldStr, String newStr) {
      template = template.replace("@{" + oldStr + "}", newStr);
   }
   
   private static String read(String path) {
      FileInputStream fstream;
      try {
         fstream = new FileInputStream(path);
         DataInputStream in = new DataInputStream(fstream);
         BufferedReader br = new BufferedReader(new InputStreamReader(in));
         String strLine;
         StringBuffer result = new StringBuffer();
         while ((strLine = br.readLine()) != null) {
            result.append(strLine);
         }
         in.close();
         return result.toString();
      } catch (FileNotFoundException e) {
         e.printStackTrace();
         return "Error finding template.";
      } catch (IOException e) {
         e.printStackTrace();
         return "IOException opening template.";
      }
   }

   public String getTemplate() {
      return template;
   }
   
}
